package com.lanchetech.admin.erp;


import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@RestController
@Api(value = "聚水潭ERP", tags = "聚水潭ERP")
@RequestMapping("/api/erp")
public class JuShuiTanUtil {

    public static final String SIGN_METHOD_MD5 = "md5";
    public static final String CHARSET_UTF8 = "utf-8";
    public static final String CONTENT_ENCODING_GZIP = "gzip";

    /**
     * 请求地址
     */
    public static String serverUrl;

    /**
     * 开放平台地址
     */
    public static String openWebUrl;

    /**
     * 应用的appKey
     */
    public static String appKey;

    /**
     * 应用的appSecret
     */
    public static String appSecret;

    @Autowired
    private JuShuiTanProperties juShuiTanProperties;

    @PostConstruct
    public void init() {
        serverUrl = juShuiTanProperties.getServerUrl();
        openWebUrl = juShuiTanProperties.getOpenWebUrl();
        appKey = juShuiTanProperties.getAppKey();
        appSecret = juShuiTanProperties.getAppSecret();
    }

    /**
     * 构建表单请求的body
     *
     * @param params
     * @param charset
     * @return
     * @throws IOException
     */
    public static String buildQuery(Map<String, String> params, String charset) throws IOException {
        if (params == null || params.isEmpty()) {
            return null;
        }

        StringBuilder query = new StringBuilder();
        Set<Map.Entry<String, String>> entries = params.entrySet();
        boolean hasParam = false;

        for (Map.Entry<String, String> entry : entries) {
            String name = entry.getKey();
            String value = entry.getValue();
            // 忽略参数名或参数值为空的参数
            if (isNotEmpty(name) && isNotEmpty(value)) {
                if (hasParam) {
                    query.append("&");
                } else {
                    hasParam = true;
                }
                query.append(name).append("=").append(URLEncoder.encode(value, charset));
            }
        }

        return query.toString();
    }


    /**
     * 对TOP请求进行签名。
     */
    public static String signTopRequest(Map<String, String> params, String secret, String signMethod) throws IOException {
        // 第一步：检查参数是否已经排序
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);

        // 第二步：把所有参数名和参数值串在一起
        StringBuilder query = new StringBuilder();
        if (SIGN_METHOD_MD5.equals(signMethod)) {
            query.append(secret);
        }
        for (String key : keys) {
            String value = params.get(key);
            if (isNotEmpty(key) && isNotEmpty(value)) {
                query.append(key).append(value);
            }
        }
        return createSign(query.toString());
    }

    /**
     * 生成新sign
     *
     * @param str 字符串
     * @return String
     */
    public static String createSign(String str) {
        if (str == null || str.length() == 0) {
            return null;
        }
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance(SIGN_METHOD_MD5);
            mdTemp.update(str.getBytes("UTF-8"));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char[] buf = new char[j * 2];
            int k = 0;
            int i = 0;
            while (i < j) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
                i++;
            }
            return new String(buf);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 店铺授权聚水潭的URL
     *
     * @return
     */
    public static String spliceAuthorizationUrl(String state) throws IOException {
        Map<String, String> params = new HashMap<String, String>();
        // 公共参数
        params.put("app_key", appKey);
        params.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        params.put("state", state);
        params.put("charset", "utf-8");
        // 签名参数
        params.put("sign", signTopRequest(params, appSecret, SIGN_METHOD_MD5));
        String url = buildQuery(params, "utf-8");
        url = openWebUrl + "/auth?" + url;
        return url;
    }

    /**
     * Function：验证签名
     *
     * @author Wangyx
     * @date 2021/12/31 12:28
     * @version 1.0.0
     */
    public static Boolean signatureVerification(Map<String, String> params, String sign) throws IOException {
        String signTopRequest = signTopRequest(params, appSecret, SIGN_METHOD_MD5);
        return sign.equals(signTopRequest);
    }

    /**
     * Function：获取accessToken
     *
     * @author Wangyx
     * @date 2021/12/31 14:23
     * @version 1.0.0
     */
    public static String getAccessToken(String code) throws IOException {
        Map<String, String> params = new HashMap<>();
        params.put("app_key", appKey);
        params.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        params.put("grant_type", "authorization_code");
        params.put("charset", "utf-8");
        params.put("code", code);
        params.put("sign", signTopRequest(params, appSecret, SIGN_METHOD_MD5));

        //获取accessToken的地址
        String url = serverUrl + "/openWeb/auth/accessToken";
        return HttpUtil.doPost(url, params.toString());
    }

    /**
     * Function：刷新AccessToken
     *
     * @author Wangyx
     * @date 2022/01/04 9:18
     * @version 1.0.0
     */
    public static String refreshToken(String refreshToken) throws IOException {
        Map<String, String> params = new HashMap<>();
        params.put("app_key", appKey);
        params.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        params.put("grant_type", "refresh_token");
        params.put("charset", "utf-8");
        params.put("refresh_token", refreshToken);
        params.put("scope", "all");
        params.put("sign", signTopRequest(params, appSecret, SIGN_METHOD_MD5));

        //获取accessToken的地址
        String url = openWebUrl + "/openWeb/auth/refreshToken";
        return HttpUtil.doPost(url, params.toString());
    }


    public static boolean isNotEmpty(String value) {
        int strLen;
        if (value == null || (strLen = value.length()) == 0) {
            return false;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(value.charAt(i)) == false)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 发送请求
     *
     * @param accessToken
     * @param biz
     * @param requestUrl
     * @return
     * @throws IOException
     */
    public static String sendRequest(String accessToken, Map<String, Object> biz, String requestUrl) throws IOException {
        // 公共请求参数
        Map<String, String> params = new HashMap<>();
        params.put("app_key", appKey);
        params.put("access_token", accessToken);
        params.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        params.put("version", "2");
        params.put("charset", "utf-8");
        // 业务参数
        params.put("biz", biz.toString());
        System.out.println(biz.toString());
        // 签名参数
        params.put("sign", signTopRequest(params, appSecret, SIGN_METHOD_MD5));
        String url = serverUrl + requestUrl;
        return HttpUtil.doPost(url, params.toString());
    }

}
